<template>
  <div>
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="用户人数" :total="userStats.total | NumberFormat">
          <a-tooltip title="用户月增长量" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div class="antv-chart-mini">
            <div class="chart-wrapper" :style="{ height: 46 }">
              <v-chart
                  :force-fit="true"
                  :height="100"
                  :data="userStats.increase"
                  :scale="[{dataKey: 'y',alias: '人数'}]"
                  :padding="['24', 'auto', '40', '50']">
                <v-tooltip/>
                <v-axis
                    dataKey="y"
                    :show="false"/>
                <v-line position="x*y"/>
                <v-point
                    position="x*y"
                    shape="circle"
                    :label="['y', {htmlTemplate: text => {return text}}]"/>
              </v-chart>
            </div>
          </div>
          <template slot="footer">本月用户增长数：
            <span v-if="userStats.increase.length > 0">
              {{ userStats.increase[userStats.increase.length - 1].y | NumberFormat }}
            </span>
            <span v-else>0</span>
          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="车辆总数" :total="bikeTotal | NumberFormat">
          <a-tooltip title="平台车辆情况" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div class="antv-chart-mini">
            <div class="chart-wrapper" :style="{ height: 46 }">
              <v-chart
                  :force-fit="true"
                  :height="100"
                  :data="bikeStats"
                  :padding="['24', 'auto', '40', '50']">
                <v-tooltip/>
                <v-axis
                    dataKey="value"
                    :show="false"/>
                <v-bar
                    position="type*value"
                    color="type"
                    :label="['value', {htmlTemplate: text => {return text}}]"/>
              </v-chart>
            </div>
          </div>
          <template slot="footer">车辆使用率：
            <span v-if="bikeStats.length > 1 && bikeStats[1].value !== undefined && bikeTotal !== 0">
              {{ (bikeStats[1].value / bikeTotal * 100).toFixed(2) }}
            </span>
            <span v-else>0</span>%
          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="充值消费">
          <a-tooltip title="充值消费情况总计" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div slot="total">
            充值：￥{{ payTotal.pay }}<br/>
            消费：￥{{ payTotal.cost }}<br/>
          </div>
          <template slot="footer">消费充值比
            <span v-if="payTotal.cost !== undefined && payTotal.pay > 0">
              {{ (payTotal.cost / payTotal.pay * 100).toFixed(2) }}
            </span>
            <span v-else>0</span>%
          </template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="骑行总时长" :total="duringText">
          <a-tooltip title="平台用户骑行总时长" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div>
          </div>
          <template slot="footer">平均单次骑行时长
            <span v-if="duringTotal.sum !== undefined && duringTotal.count > 0">
              {{ Math.floor(duringTotal.sum / duringTotal.count) }}
            </span>
            <span v-else>0</span>分钟
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading2" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a @click="handleDuringAndCost(0)">今日</a>
              <a @click="handleDuringAndCost(1)">本周</a>
              <a @click="handleDuringAndCost(2)">本月</a>
              <a @click="handleDuringAndCost(3)">今年</a>
            </div>
          </div>
          <a-tab-pane loading="true" tab="骑行时间和消费统计" key="1">
            <a-row>
              <a-col :span="24">
                <v-chart
                    :force-fit="true"
                    height="405"
                    :padding="['24', '100', '80', '100']"
                    :scale="[{dataKey: 'during',alias: '骑行时间'}, {dataKey: 'cost',alias: '消费金额'}]"
                    :data="duringAndCost">
                  <v-tooltip/>
                  <v-legend
                      :custom="legendCustom"
                      :allow-all-canceled="legendAllowAllCanceled"
                      :items="legendItems"
                      :itemFormatter="itemFormatter"
                      :on-click="legendOnClick"
                  />
                  <v-axis
                      data-key="during"
                      :label="duringLabel"
                  />
                  <v-axis
                      data-key="cost"
                      :grid="null"
                      :label="costLabel"
                  />
                  <v-line position="index*during" color="#1890FF"/>
                  <v-point shape="circle" position="index*during" color="#1890FF"/>
                  <v-line position="index*cost" color="#52C41A"/>
                  <v-point shape="circle" position="index*cost" color="#52C41A"/>
                </v-chart>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
  </div>
</template>

<script>

import moment from 'moment'
import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  RankList,
  Bar,
  Trend,
  NumberInfo,
  MiniSmoothArea
} from '@/components'
import {
  queryBikeStatsTotal,
  queryDuringAndCost,
  queryDuringTotal,
  queryPayTotal,
  queryUserStats
} from "@/api/basic/statistics";

let that
let fieldMap = {
  during: '骑行时间',
  cost: '消费金额',
}

export default {
  name: 'Analysis',
  components: {
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    RankList,
    Bar,
    Trend,
    NumberInfo,
    MiniSmoothArea
  },
  data () {
    return {
      userStats: {
        total: 0,
        increase: []
      },
      payTotal: {},
      payTotalText: '',
      bikeStats: {},
      bikeTotal: 0,
      loading: true,
      loading2: true,
      duringTotal: {},
      duringText: '',
      duringAndCost: [],
      duringLabel: {
        textStyle: {fill: '#1890FF'},
        formatter (val) {
          return val + '分钟'
        }
      },
      costLabel: {
        textStyle: {fill: '#52C41A'},
        formatter (val) {
          return val + '元'
        }
      },
      weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      sections: ['点', '', '日', '月'],
      bikeStates: ['未使用', '使用中', '维修中', '报废'],
      recordTypes: ['消费', '充值', '违约金'],

      gemoSize: 3,
      legendCustom: true,
      legendAllowAllCanceled: true,
      legendItems: [
        {value: 'during', marker: {symbol: 'circle', fill: '#1890FF'}},
        {value: 'cost', marker: {symbol: 'circle', fill: '#52C41A'}}
      ],
      itemFormatter (val) {
        return fieldMap[val]
      },
      legendOnClick: (ev, chart) => {
        const item = ev.item;
        const value = item.value;
        const checked = ev.checked;
        const geoms = chart.getAllGeoms();
        for (let i = 0; i < geoms.length; i++) {
          const geom = geoms[i];
          if (geom.getYScale().field === value) {
            if (checked) {
              geom.show();
            } else {
              geom.hide();
            }
          }
        }
      },
    }
  },
  beforeCreate () {
    that = this
  },
  created () {
    this.handleData()
  },
  methods: {
    handleData () {
      this.loading = true
      this.handleUserStats()
      this.handleBikeStatsTotal()
      this.handlePayTotal()
      this.handleDuringTotal()
      this.handleDuringAndCost(1)
      setTimeout(() => {
        this.loading = false
      }, 1000)
    },
    handleUserStats () {
      queryUserStats().then(res => {
        if (res.message === 'success') {
          let data = res.result
          for (let i of data.increase) {
            i.x = i.x + '月'
          }
          this.userStats = data
        }
      }).catch(err => {
        // this.$message.error('查询统计信息失败')
      })
    },
    handleBikeStatsTotal () {
      queryBikeStatsTotal().then(res => {
        if (res.message === 'success') {
          let data = res.result
          data.sort((p, q) => {
            return p.type - q.type
          })
          this.bikeTotal = 0
          for (let i of data) {
            i.type = this.bikeStates[i.type]
            this.bikeTotal += i.value
          }
          this.bikeStats = data
        }
      }).catch(err => {
        // this.$message.error('查询统计信息失败')
      })
    },
    handlePayTotal () {
      queryPayTotal().then(res => {
        if (res.message === 'success') {
          let data = res.result
          let type0, type1
          for (let i of data) {
            if (i.type === 0) {
              type0 = i.value
            } else if (i.type === 1) {
              type1 = i.value
            }
          }
          this.payTotal = {
            cost: type0,
            pay: type1,
          }
        }
      }).catch(err => {
        // this.$message.error('查询统计信息失败')
      })
    },
    handleDuringTotal () {
      queryDuringTotal().then(res => {
        if (res.message === 'success') {
          this.duringTotal = res.result
          let hour = Math.floor(this.duringTotal.sum / 60)
          let day = Math.floor(hour / 24)
          this.duringText = day + ' 天 '
              + (hour - day * 24 + 1) + ' 小时 '
        }
      }).catch(err => {
        // this.$message.error('查询统计信息失败')
      })
    },
    handleDuringAndCost (type) {
      this.loading2 = true
      queryDuringAndCost({type: type}).then(res => {
        if (res.message === 'success') {
          let data = res.result
          if (type === 1) {
            for (let i of data) {
              i.index = this.weekDays[i.index]
            }
          } else if (type === 0) {
            for (let i of data) {
              i.index = i.index + this.sections[type]
            }
          } else {
            for (let i of data) {
              i.index = (i.index + 1) + this.sections[type]
            }
          }
          this.duringAndCost = data
          this.loading2 = false
        }
      }).catch(err => {
        this.loading2 = false
        // this.$message.error('查询统计信息失败')
      })
    },
  }
}
</script>


<style lang="less" scoped>
@import "../../components/charts/chart";

.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

.antd-pro-pages-dashboard-analysis-twoColLayout {
  position: relative;
  display: flex;
  flex-flow: row wrap;
}

.antd-pro-pages-dashboard-analysis-salesCard {
  height: calc(100% - 24px);

  /deep/ .ant-card-head {
    position: relative;
  }
}

.dashboard-analysis-iconGroup {
  i {
    margin-left: 16px;
    color: rgba(0, 0, 0, .45);
    cursor: pointer;
    transition: color .32s;
    color: black;
  }
}

.analysis-salesTypeRadio {
  position: absolute;
  right: 54px;
  bottom: 12px;
}
</style>
